import 'package:flutter/material.dart';
import 'package:personinfo/model/home/SearchCarModel.dart';
import 'package:personinfo/utils/ColorUtil.dart';
import 'package:personinfo/utils/DialogUtil.dart';
import 'package:personinfo/utils/commonUtil.dart';
import 'package:personinfo/widgets/common/CommonWidget.dart';
import 'package:personinfo/widgets/common/LineNav.dart';
import 'package:personinfo/widgets/common/MiniTitleNav.dart';
import 'package:personinfo/widgets/common/Vanfeild.dart';

class PublishSearchCar extends StatefulWidget{
  SearchCarModel arguments;
  PublishSearchCar({super.key, required this.arguments});

  @override
  State<StatefulWidget> createState()=>_PublishSearchCar();

}

class _PublishSearchCar extends State<PublishSearchCar>{
  final _formKey = GlobalKey<FormState>(); // 创建一个表单键
  late  int groupValue = 2;
  String? validDay="1天";
  int ? validIndex = 0;

  List chooseList = [
    {"label": "优惠点数","desc": "点","placeholder":"请填写期望优惠点数"},
    {"label": "优惠金额","desc": "万","placeholder":"请填写期望优惠金额"},
    {"label": "加价点数","desc": "点","placeholder":"请填写期望加价点数"},
    {"label": "加价金额","desc": "万","placeholder":"请填写加价金额"},
    {"label": "直接报价","desc": "万","placeholder":"请填写直接报价"},
    {"label": "电议","desc": "电议","placeholder":""},
  ];

  _listInfo(){
    return  ListView.builder(
          shrinkWrap: true,
          itemCount: chooseList.length,
          physics: const ClampingScrollPhysics(),
          itemBuilder: (BuildContext context, int index){
            return SizedBox(
              height: 46,
              child: RadioListTile(
                  value: index,
                  activeColor: ColorUtil.primaryBadgeBgColor,
                  contentPadding: EdgeInsets.symmetric(horizontal: 0, vertical: 4),
                  dense: true,
                  visualDensity: VisualDensity.compact,
                  title: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    verticalDirection: VerticalDirection.up,
                    children: [
                      Flexible(flex: 1,
                          child: Text(
                              chooseList[index]["label"],
                              style: TextStyle(
                                  color: groupValue == index ? Colors.black : Colors.grey.shade400
                              )
                          )
                      ),
                      if(chooseList[index]["placeholder"] !="" && groupValue == index)
                        Expanded(
                            flex: 2,
                            child:SizedBox(
                              height: 40,
                              child: TextField(
                                decoration: InputDecoration(
                                  hintText: chooseList[index]["placeholder"],
                                  hintStyle: TextStyle(fontSize: 14),
                                  border: CommonUtil.underline,
                                  focusedBorder: CommonUtil.underline,
                                ),
                              ),
                            )
                        ),
                      if(groupValue == index)
                        Flexible(child: Text(chooseList[index]["desc"]))
                    ],
                  ),
                  groupValue: groupValue,
                  onChanged: (index){
                    setState(() {
                      groupValue = index!;
                    });
                  }),
            );
          }
    );
  }


  @override
  Widget build(BuildContext context) {

    return PopScope(
        canPop: false, // 可选：完全禁止 pop（包括按钮和手势）
        onPopInvokedWithResult: (bool didPop, Object? result){
          // 如果已经 pop 了（比如用户确认后手动 pop），直接返回
          if (didPop) return;
            // 注意：这里要调用 pop，并传入 result（可选）
            // 这会再次触发 onPopInvokedWithResult，但 didPop = true
            Navigator.popAndPushNamed(context, "/");
           print("右滑!");
        },

      child: Scaffold(
        backgroundColor: Theme.of(context).colorScheme.onPrimary,
        appBar: commonWidget.appBar(
          leading: GestureDetector(onTap: (){Navigator.popAndPushNamed(context, "/");;},child: const Icon(Icons.keyboard_arrow_left),),
          title: const Text("发布寻车") ,
        ),
        body: SingleChildScrollView(
          child: Form(
              key: _formKey,
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.fromLTRB(16 , 10, 16, 10),
                    child: Column(
                      children: [
                        const MiniTitleNav(title: "必填字段",marginLeft: 0,),
                        Vanfeild(labelText: '车型',onTap: () async {
                          Navigator.pushNamed(context, "/selectCarBrand", arguments: widget?.arguments);
                        },val: widget?.arguments?.carBrand ?? ""),
                        Vanfeild(labelText: '车规',placeholder: "-",showIcon: false,val: widget?.arguments?.carRule??""),
                        Vanfeild(labelText: '外观/内饰',
                            onTap: () async {
                              Navigator.pushNamed(context, "/selectCarInterior", arguments: widget?.arguments);
                            },
                            val: widget.arguments?.carInterior??""
                        ),
                        const SizedBox(height: 20),
                        _listInfo(),
                        const SizedBox(height: 10,),
                        const Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("期望成交价",style: TextStyle(fontWeight: FontWeight.bold),),
                            Text("-"),
                          ],
                        ),
                        SizedBox(height: 16,),
                        const Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("官方指导价",style: TextStyle(fontWeight: FontWeight.bold),),
                            Text("-"),
                          ],
                        ),
                        SizedBox(height: 10,),

                      ],
                    ),
                  ),
                  lineNav.heightLine(),
                  Container(
                    padding: const EdgeInsets.fromLTRB(16 , 10, 16, 10),
                    child: Column(
                      children: [
                        const MiniTitleNav(title: "选填信息",marginLeft: 0,),
                        Vanfeild(labelText: '寻车有效期',val: validDay,onTap: () async {
                          var option = [
                            {'label': '3天'},
                            {'label': '15天'},
                            {'label': '30天'},
                            {'label': '90天'},
                          ];
                          // 调用示例
                          dialogUtils.showBottomSheetOptions(
                              context,
                              option,
                              selectedIndex: validIndex,
                              onSelected: (index) {
                                print('选中了选项: $index');
                                setState(() {
                                  validIndex = index;
                                  validDay = option[index]["label"];
                                });
                              }
                          );

                        }),
                        Vanfeild(labelText: '上牌地点',
                            onTap: () async {

                            },
                            val: widget.arguments?.locationProvince ?? ""
                        ),
                        Vanfeild(labelText: '票证要求'),
                        const TextField(
                          maxLines: 4,
                          maxLength: 150,
                          decoration: InputDecoration(
                              hintText: "请填写其他没有列出的寻车要求。完整的信息有助于我们为您匹配车源。",
                              helperText: "请填写其他没有列出的寻车要求。完整的信息有助于我们为您匹配车源。",
                              labelText: "寻车人备注：",
                              labelStyle:TextStyle(color: Colors.black,fontSize: 14),
                              focusedBorder: CommonUtil.underline
                          ),
                        ),
                        MiniTitleNav(title: "温馨提示",marginLeft: 0,),
                        Text("您发布寻车后，微购专属客服将核实车源情况并尽快与您联系，请保持手机通畅。",style: TextStyle(color: Color.fromRGBO(254, 140, 114, 1)),),
                        SizedBox(height: 20,)
                      ],
                    ),
                  ),

                  Flex(
                    direction: Axis.horizontal,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      commonWidget.btnBox(title:"确认发布",onTap: (){

                      }),
                      commonWidget.btnBox(title:"专属客服", color: Color.fromRGBO(165, 165, 165, 1), onTap: (){

                      }),
                    ],
                  )
                ],
              )
          ),
        ),
      ),
    );
  }

}